package cn.peng.stu4teach.bizutil.http;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import cn.peng.stu4teach.util.http.HttpUtils;

/**
 * 对象型响应数据
 */
public abstract class BizHttpGsonRe<T> implements HttpUtils.IHttpRe {
    private final Class<T> cls;

    public BizHttpGsonRe (Class<T> cls) {
        this.cls = cls;
    }

    /**
     * respone 的响应示例
     * {
     *     "data": {
     *         "curPage": 2,
     *         "datas": [
     *             {
     *                 "link": "https://peng.cn/post/7344571968174669876",
     *                 "niceShareDate": "2024-06-03 09:40",
     *                 "shareUser": "CnPeng",
     *                 "title": "全局视角下的APP性能优化经验",
     *             }
     *         ],
     *         "offset": 20,
     *         "over": false,
     *         "pageCount": 773,
     *         "size": 20,
     *         "total": 15452
     *     },
     *     "errorCode": 0,
     *     "errorMsg": ""
     * }
     */
    @Override
    public void onHttpReSuccess (@NonNull String response) {
        // 先转换成标准的 JsonObject,判断业务响应成功还是失败。
        JsonObject jsonObject = GsonUtils.fromJson(response, JsonObject.class);
        //LogUtils.d("BaseHttpRe", jsonObject.toString());
        JsonElement errorCode = jsonObject.get("errorCode");
        if (errorCode.getAsInt() != 0 ) {
            onError(jsonObject.get("errorMsg").getAsString());
            return;
        }

        // 读取 data 并解析为 cls 类型的数据
        JsonElement jsonElement = jsonObject.get("data");
        String dataStr = GsonUtils.toJson(jsonElement);
        if (TextUtils.isEmpty(dataStr)){
            onError("服务端响应数据有误——data为空");
            return;
        }
        T data = GsonUtils.fromJson(dataStr,cls);
        if (null != data) {
            onSuccess(data);
        } else {
            onError("解析data为结构体出错");
        }
    }

    @Override
    public void onHttpReError (String errorMessage) {
        onError(errorMessage);
    }

    protected abstract void onSuccess (@NonNull T pReData);

    protected abstract void onError (@NonNull String pErrMsg);
}
